package cz.hanis.android.pubaccounting.db;

import java.util.List;

import cz.hanis.android.pubaccounting.db.dao.ItemDao;
import cz.hanis.android.pubaccounting.db.dao.PubDao;
import cz.hanis.android.pubaccounting.model.Item;
import cz.hanis.android.pubaccounting.model.Pub;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.SystemClock;
import android.util.Log;

public class DbManagerImpl implements DbManager {

	private Context context;
	private SQLiteDatabase db;

	private PubDao pubDao;
	private ItemDao itemDao;

	public DbManagerImpl(Context context) {
		this.context = context;
		SQLiteOpenHelper dbOpenHelper = new DbOpenHelper(this.context);
		db = dbOpenHelper.getWritableDatabase();
		Log.i(DbConstants.LOG_TAG, "DbManagerImpl created, db open status: "
				+ db.isOpen());

		pubDao = new PubDao(db);
		itemDao = new ItemDao(db);

	}

	public SQLiteDatabase getDb() {
		return db;
	}

	private void openDb() {
		if (!db.isOpen()) {
			db = SQLiteDatabase.openDatabase(DbConstants.DATABASE_PATH, null,
					SQLiteDatabase.OPEN_READWRITE);
			pubDao = new PubDao(db);
			itemDao = new ItemDao(db);
		}
	}

	private void closeDb() {
		if (db.isOpen()) {
			db.close();
		}
	}

	private void resetDb() {
		Log.i(DbConstants.LOG_TAG,
				"Resetting database connection (close and re-open).");
		closeDb();
		SystemClock.sleep(500);
		openDb();
	}

	@Override
	public Pub getPub(long id) {
		Pub pub = pubDao.get(id);
		if (pub != null) {
			pub.getItems().addAll(itemDao.getItems(pub.getId()));
		}
		return pub;
	}

	@Override
	public List<Pub> getPubHeaders() {
		return pubDao.getAll();
	}

	@Override
	public long savePub(Pub pub) {
		return pubDao.save(pub);
	}

	@Override
	public void updatePub(Pub pub) {
		pubDao.update(pub);
	}

	@Override
	public void deletePub(Pub pub) {
		pubDao.delete(pub);
	}

	@Override
	public Item getItem(long id) {
		return itemDao.get(id);
	}

	@Override
	public long saveItem(Item item) {
		return itemDao.save(item);
	}

	@Override
	public void updateItem(Item item) {
		itemDao.update(item);
	}

	@Override
	public void deleteItem(Item item) {
		itemDao.delete(item);
	}

}
